package com.hps.demo.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @Author hps
 * @Description:
 * @Date Created in 20:13 2019/7/11
 */
public class RegisterCenterWithZk implements RegisterCenter {

    CuratorFramework client = null;

    {
        client = CuratorFrameworkFactory.builder()
                .connectString("192.168.26.143:2181")
                .namespace("registry")
                .connectionTimeoutMs(2000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        client.start();
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        String path = "/" + serviceName;
        try {
            if (client.checkExists().forPath(path) == null) {
                client.create().creatingParentContainersIfNeeded()
                        .withMode(CreateMode.PERSISTENT).forPath(path);
            }
            String providerPath = path + "/" + serviceAddress;
            client.create().withMode(CreateMode.EPHEMERAL).forPath(providerPath);
            System.out.println("服务" + serviceName + "注册成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        if (client != null) {
            client.close();
        }
    }
}
